package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping
    public R<String> save(@RequestBody Category category, HttpSession session) {
        //1.获取登录人数据
        Employee employee = (Employee) session.getAttribute("employee");
        //2.完善Category信息
        //创建人
        category.setCreateUser(employee.getId());
        //修改人
        category.setUpdateUser(employee.getId());

        //3.调用业务添加操作
        categoryService.save(category);
        //4.封装结果返回
        return R.success("添加成功");

    }

    @GetMapping("/page")
    public R<Page<Category>> findByPage(Integer page, Integer pageSize) {
        Page<Category> pageObj = categoryService.findByPage(page, pageSize);

        return R.success(pageObj);
    }

    @DeleteMapping
    public R<String> delete(long id) {
        categoryService.delete(id);

        return R.success("删除成功");
    }
    @PutMapping
    public R<String> update(@RequestBody Category category, HttpSession session) {
        //l/1.获取登录员工
        Employee employee = (Employee) session.getAttribute("employee");
        //2.完善信息（修改人)category.setUpdateUser
        category.setUpdateUser(employee.getId());
        //3.调用业务操作
        categoryService.update(category);
        //4.封装结果返回
        return R.success("修改成功");
    }
    @GetMapping("/list")
    public R<List<Category>> findAllByType(Integer type){
        List<Category> categoryList = categoryService.findAllByType(type);

        return R.success(categoryList);
    }

}